package controller;

import model.UserInfo;
import model.UserNameToId;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: a
 * Date: 2022-12-07
 * Time: 15:32
 */
@WebServlet("/register")
public class Register extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        //字符串哈希(将用户名转化成id)
        UserNameToId userNameToId = new UserNameToId();
        int userId = userNameToId.getId(name);
        System.out.println(userId);
        if(name == null || password == null || name.equals("") || password.equals("")){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("输入的用户名或者密码不能为空");

            return;
        }
        //判断这个账户是否已经存在
        if(UserInfo.users[userId] != null){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("无法注册: 此账户已经存在");
            return;
        }
        UserInfo userInfo = new UserInfo();
        userInfo.insert(userId, name, password);
        resp.sendRedirect("login.html");
    }
}
